﻿namespace Huayou.Utils
{
    using System;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Text;
    using System.Web;

    public class ValidaterCode
    {
        private static Random _rnd = null;
        private static object _rndLock = new object();
        private const string DEFAULT_CHAR = "0123456789";
        private const int DEFAULT_LENGTH = 4;

        public static void CreateImage(HttpResponse response, string checkCode)
        {
            int width = (int) (checkCode.Length * 11.5);
            Bitmap image = new Bitmap(width, 20);
            Graphics graphics = Graphics.FromImage(image);
            Font font = new Font("Arial", 10f, FontStyle.Bold);
            Brush brush = new SolidBrush(Color.Red);
            graphics.Clear(Color.White);
            graphics.DrawString(checkCode, font, brush, (float) 3f, (float) 3f);
            Pen pen = new Pen(Color.Black, 0f);
            Random random = new Random();
            MemoryStream stream = new MemoryStream();
            image.Save(stream, ImageFormat.Jpeg);
            response.ClearContent();
            response.ContentType = "image/Jpeg";
            response.BinaryWrite(stream.ToArray());
            graphics.Dispose();
            image.Dispose();
        }

        public static string CreateRandomCode()
        {
            return CreateRandomCode(4, "0123456789");
        }

        public static string CreateRandomCode(int codeCount)
        {
            return CreateRandomCode(codeCount, "0123456789");
        }

        public static string CreateRandomCode(string allChar)
        {
            return CreateRandomCode(4, allChar);
        }

        public static string CreateRandomCode(int codeCount, string allChar)
        {
            lock (_rndLock)
            {
                if (_rnd == null)
                {
                    _rnd = new Random();
                }
            }
            char[] chArray = allChar.ToCharArray();
            StringBuilder builder = new StringBuilder();
            int num = -1;
            int length = allChar.Length;
            for (int i = 0; i < codeCount; i++)
            {
                int index = _rnd.Next(length);
                while (num == index)
                {
                    index = _rnd.Next(length);
                }
                num = index;
                builder.Append(chArray[index]);
            }
            return builder.ToString();
        }
    }
}

